package day4;

import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int[] arr = {3, 6, 9, 12, 77, 99, 123};

        boolean exit = true;

        while (exit) {
            System.out.println("输入你要找的数字");
            int num = sc.nextInt();

            int key = binary_search(arr, num, 0, arr.length - 1);
            System.out.println(key);

            System.out.println("是否继续？ 继续:true 取消:false");
            exit = sc.nextBoolean();
        }
    }

    public static int binary_search(int[] nums, int target, int left, int right){

        int middle = (left + right) / 2;
        if (target < nums[0] || target > nums[nums.length - 1]){
            return 0;
        }

        if (nums[middle] == target) {
            return middle;
        } else if (nums[middle] < target) {
            return binary_search(nums, target, middle, right + 1);
        } else if (nums[middle] > target) {
            return binary_search(nums, target, left, middle);
        } else {
            return 0;
        }
    }
}
